package com.atao.baokede.utils;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.Scanner;
import java.util.stream.Collectors;

//关于验证码的工具类
public class CodeUtil {
    //生成指定长度的的验证码
    public static String generateCode(int length) {
        return new Random().ints(length, 0, 10)
                .mapToObj(String::valueOf)
                .collect(Collectors.joining());
    }

    //获取带有验证码的HTML格式字符串
    public static String getHtmlWithCode(String code) throws Exception {
        // 使用类路径读取资源文件
        InputStream inputStream = CodeUtil.class.getClassLoader()
                .getResourceAsStream("static/code.html");

        if (inputStream == null) {
            throw new RuntimeException("无法找到资源文件: static/code.html");
        }

        // 读取流为字符串
        String htmlContent;
        try (Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
            htmlContent = scanner.useDelimiter("\\A").next();
        }

        // 替换模板中的占位符
        return htmlContent.replace("{{code}}", code);
    }
}